import json
from typing import Dict, List, Any, Optional
from django.db import transaction
from .models import DriverImprovementMemory

class DriverMemoryService:
    """司机改进记忆服务 - 重构memory模式实现"""
    
    def __init__(self, driver_id: int):
        self.driver_id = driver_id
    
    def store_memory(self, memory_type: str, memory_key: str, memory_value: Any, importance_score: float = 1.0) -> bool:
        """
        存储记忆
        
        Args:
            memory_type: 记忆类型 (e.g., 'rating_history', 'improvement_record', 'training_completion')
            memory_key: 记忆键 (e.g., 'service_attitude', 'driving_skill')
            memory_value: 记忆值 (可以是任何JSON可序列化的数据)
            importance_score: 重要性得分 (0.0-1.0)
        
        Returns:
            bool: 是否成功存储
        """
        try:
            with transaction.atomic():
                memory, created = DriverImprovementMemory.objects.update_or_create(
                    driver_id=self.driver_id,
                    memory_type=memory_type,
                    memory_key=memory_key,
                    defaults={
                        'memory_value': memory_value,
                        'importance_score': importance_score
                    }
                )
                return True
        except Exception as e:
            print(f"存储记忆失败: {e}")
            return False
    
    def retrieve_memory(self, memory_type: str, memory_key: str) -> Optional[Any]:
        """
        检索记忆
        
        Args:
            memory_type: 记忆类型
            memory_key: 记忆键
        
        Returns:
            记忆值或None
        """
        try:
            memory = DriverImprovementMemory.objects.filter(
                driver_id=self.driver_id,
                memory_type=memory_type,
                memory_key=memory_key
            ).first()
            return memory.memory_value if memory else None
        except Exception as e:
            print(f"检索记忆失败: {e}")
            return None
    
    def retrieve_memories_by_type(self, memory_type: str, limit: int = 10) -> List[Dict[str, Any]]:
        """
        根据类型检索记忆列表
        
        Args:
            memory_type: 记忆类型
            limit: 返回数量限制
        
        Returns:
            记忆列表
        """
        try:
            memories = DriverImprovementMemory.objects.filter(
                driver_id=self.driver_id,
                memory_type=memory_type
            ).order_by('-importance_score', '-last_updated')[:limit]
            
            return [
                {
                    'memory_key': memory.memory_key,
                    'memory_value': memory.memory_value,
                    'importance_score': memory.importance_score,
                    'last_updated': memory.last_updated
                }
                for memory in memories
            ]
        except Exception as e:
            print(f"检索记忆列表失败: {e}")
            return []
    
    def update_importance_score(self, memory_type: str, memory_key: str, new_score: float) -> bool:
        """
        更新记忆的重要性得分
        
        Args:
            memory_type: 记忆类型
            memory_key: 记忆键
            new_score: 新的重要性得分
        
        Returns:
            bool: 是否成功更新
        """
        try:
            updated = DriverImprovementMemory.objects.filter(
                driver_id=self.driver_id,
                memory_type=memory_type,
                memory_key=memory_key
            ).update(importance_score=new_score)
            return updated > 0
        except Exception as e:
            print(f"更新重要性得分失败: {e}")
            return False
    
    def delete_memory(self, memory_type: str, memory_key: str) -> bool:
        """
        删除记忆
        
        Args:
            memory_type: 记忆类型
            memory_key: 记忆键
        
        Returns:
            bool: 是否成功删除
        """
        try:
            deleted, _ = DriverImprovementMemory.objects.filter(
                driver_id=self.driver_id,
                memory_type=memory_type,
                memory_key=memory_key
            ).delete()
            return deleted > 0
        except Exception as e:
            print(f"删除记忆失败: {e}")
            return False
    
    def get_driver_profile(self) -> Dict[str, Any]:
        """
        获取司机改进档案
        
        Returns:
            司机改进档案数据
        """
        try:
            # 获取各种类型的记忆
            rating_history = self.retrieve_memories_by_type('rating_history', 20)
            improvement_records = self.retrieve_memories_by_type('improvement_record', 10)
            training_completion = self.retrieve_memories_by_type('training_completion', 10)
            
            return {
                'driver_id': self.driver_id,
                'rating_history': rating_history,
                'improvement_records': improvement_records,
                'training_completion': training_completion,
                'profile_summary': self._generate_profile_summary(rating_history, improvement_records, training_completion)
            }
        except Exception as e:
            print(f"获取司机档案失败: {e}")
            return {'driver_id': self.driver_id, 'error': str(e)}
    
    def _generate_profile_summary(self, rating_history: List, improvement_records: List, training_completion: List) -> Dict[str, Any]:
        """
        生成档案摘要
        
        Args:
            rating_history: 评价历史
            improvement_records: 改进记录
            training_completion: 培训完成情况
        
        Returns:
            档案摘要
        """
        # 计算平均评分
        if rating_history:
            avg_rating = sum(item['memory_value'].get('rating', 0) for item in rating_history) / len(rating_history)
        else:
            avg_rating = 0
        
        # 统计改进领域
        improvement_areas = {}
        for record in improvement_records:
            area = record['memory_value'].get('area', 'unknown')
            improvement_areas[area] = improvement_areas.get(area, 0) + 1
        
        # 统计培训完成情况
        completed_trainings = len([t for t in training_completion if t['memory_value'].get('status') == 'completed'])
        total_trainings = len(training_completion)
        
        return {
            'average_rating': round(avg_rating, 2),
            'total_ratings': len(rating_history),
            'improvement_areas': improvement_areas,
            'training_completion_rate': round(completed_trainings / total_trainings * 100, 2) if total_trainings > 0 else 0,
            'completed_trainings': completed_trainings,
            'total_trainings': total_trainings
        } 